# -*- coding: utf-8 -*-
import json
import os

import wx

REPOSITORY = 'repository'

LOCAL = 'local'

PASSWORD = 'password'

USER = 'user'

URL = 'url'

# 用户目录
HOME_DIR = wx.GetHomeDir()

# 项目文件夹
PROJECT_FOLDER = '.PiatoSvnKit'

# 项目配置文件
PROJECT_JSON = 'project.json'

# 项目配置文件文件夹
PROJECT_CONFIG_FOLDER_FULL_PATH = os.path.join(HOME_DIR, PROJECT_FOLDER)

# 项目全路径
PROJECT_CONFIG_FULL_PATH = os.path.join(HOME_DIR, PROJECT_FOLDER, PROJECT_JSON)


class Project:

    def __init__(self, name, url, usr, pwd, path):
        self.name = name
        self.url = url
        self.usr = usr
        self.pwd = pwd
        self.path = path

    # 生成项目配置字符串
    def to_config(self):
        return {REPOSITORY: {URL: self.url, USER: self.usr,PASSWORD: self.pwd}, LOCAL: self.path}


class ConfigParser:

    def __init__(self):
        self.config = {}
        self.load_config()

    # 加载配置信息
    def load_config(self):

        if not os.path.exists(PROJECT_CONFIG_FOLDER_FULL_PATH):
            os.makedirs(PROJECT_CONFIG_FOLDER_FULL_PATH)

        if os.path.exists(PROJECT_CONFIG_FULL_PATH):
            fp = open(PROJECT_CONFIG_FULL_PATH)
            self.config = json.load(fp)
            fp.close()

    # 获得项目列表,没有配置信息
    def get_project_list(self):
        return [k for k in self.config]

    # 将新配置写到硬盘
    def persist_config(self):
        fp = open(PROJECT_CONFIG_FULL_PATH, 'w+')
        json.dump(self.config, fp, indent=4)
        # json.dump(self.config, fp)
        fp.close()

    # merge新配置到已有配置中,重复配置覆盖
    def merge_config(self, pro):
        self.config[pro.name] = pro.to_config()

    # 返回全部格式
    def get_config(self):
        return self.config

    # 获得项目配置,dictionary格式
    def get_prj_config(self, prj_name):
        return self.config[prj_name]

    # 是否存在同名项目
    def exists(self, pro):
        return pro.name in self.config

    def del_prj_config(self, prj_name):
        del self.config[prj_name]

'''parser = ConfigParser()

print parser.get_project_list()

prj = Project()
prj.build('name', 'url', 'wanggy', 'password', '/User/wangguangyu/.....')

parser.merge_config(prj)

parser.persist_config()
'''
